package mysql

import (
	"fmt"
	"gorm.io/gorm"
	"week1/server/global"
	"week1/server/request"
)

type UserWeek1 struct {
	gorm.Model
	Username string `gorm:"type:varchar(20);comment:账号;index;unique;"`
	Password string `gorm:"type:varchar(32);comment:密码;"`
	Sex      int    `gorm:"type:tinyint(1);comment:性别;"`
	Email    string `gorm:"type:varchar(20);comment:邮箱;"`
	Status   int    `gorm:"type:tinyint(1);comment:状态;"`
	Mobile   string `gorm:"type:char(11);comment:手机号;index;"`
}

// 添加
func CreateUser(user request.CreateUserRequest) error {
	data := UserWeek1{
		Username: user.Username,
		Password: user.Password,
		Sex:      user.Sex,
		Email:    user.Email,
		Status:   user.Status,
		Mobile:   user.Mobile,
	}
	return global.DB.Create(&data).Error
}

// 查询
func IdUserInfo(user request.DeleteUserInfo) (UserWeek1, error) {
	var data UserWeek1
	err := global.DB.Where("id = ?", user.Id).First(&data).Error
	if err != nil {
		fmt.Println("查询失败", err)
	}
	return data, err
}

// 列表展示 (根据用户名搜索)
func GetUserList(user request.GetUserListRequest) ([]*UserWeek1, error) {
	var list []*UserWeek1
	err := global.DB.Where("username like ?", "%"+user.Username+"%").Find(&list).Error
	return list, err
}

// 修改用户信息 （编辑）

func UpdateUserInfo(user request.UpdateUserInfo) error {
	data := UserWeek1{
		Model:    gorm.Model{ID: uint(user.Id)},
		Username: user.Username,
		Password: user.Password,
		Sex:      user.Sex,
		Email:    user.Email,
		Status:   user.Status,
		Mobile:   user.Mobile,
	}
	err := global.DB.Where("id = ?", user.Id).Updates(&data).Error
	if err != nil {
		fmt.Println("修改失败", err)
	}
	return err
}

// 删除用户信息

func DeleteUserInfo(user request.DeleteUserInfo) error {
	data := UserWeek1{
		Model: gorm.Model{ID: uint(user.Id)},
	}
	err := global.DB.Where("id = ?", user.Id).Delete(&data).Error
	if err != nil {
		fmt.Println("删除失败", err)
	}
	return err
}
